<template>
  <div class="content-box">
    <heading grade="1">{{titleList[step - 1]}}</heading>
    <div v-show="step ==1">

      <el-row class="top-line">
        <el-col class="text-right" :span="4">
          当前参赛者数量：
      </el-col>
      <el-col :span="5">
        <span class="team-num">{{race_cup_teams.length}}</span>
      </el-col>
      </el-row>

      <el-form ref="form1" :model="form1" :rules="rules">
        <el-form-item label=""          
          :rules="[
               { required: true, message: '请设置分组数量'},
          ]">
          <el-row>
            <el-col class="text-right" :span="4">
              <label>需要分组数量：</label>
            </el-col>
            <el-col :span="5">
              <el-input-number :min="1" :max="32"  v-model="form1.groupCount"></el-input-number>
            </el-col>            
          </el-row>
        </el-form-item>
        <el-form-item label="">
          <el-row>
            <el-col class="text-right" :span="4">
              <label>每组平均数量：</label>
            </el-col>
            <el-col :span="5">
              <p style="padding-left:5px;">{{avgCount}}</p>
            </el-col>
            <el-col :span="9">
              <p class="inline tips">*{{warnText}}</p>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label=""
          prop="groupCount"
          :rules="[
               { required: true, message: '请设置每组最少出线数量'},
          ]">
          <el-row>
            <el-col class="text-right" :span="4">
              <label>出线数量：</label>
            </el-col>
            <el-col :span="5"
              prop="outletCount"
              :rules="[
                  { required: true,  message: '请设置出线数量'},
              ]">
              <el-input-number  v-model="form1.outletCount"></el-input-number>
            </el-col>
            <el-col :span="9">
              <p class="inline tips">*{{warnText1}}</p>
            </el-col>
          </el-row>        
        </el-form-item>
      </el-form>
      <div class="btn-groups center">
        <el-button size="large" type="primary" @click="submitForm('form1')">下一步</el-button>
      </div>
    </div>

    <div v-show="step >= 2">
      <GroupSlider
        :value="activeGroup"
        :list="race_cup_groups"
        :slides="8"
        @change="handleChange"
        :height="'38px'">
        <template scope="scope">
          <p style="line-height:36px;">{{scope.groupName}}组</p>
        </template>
      </GroupSlider>

      <div v-show="step == 2">
        <div class="group-teams">
          <GroupTeam
            :value="groupList" 
            :teamIndex="currentGroupIndex"
            @valueChange="handleSelect">
          </GroupTeam>
          <div class="left-team">待分配数量：<span>{{race_cup_teams.length - unSelect}}</span></div>
        </div>
        <div class="btn-group center">
          <el-button type="primary" @click="step=1">上一步</el-button>
          <el-button type="primary" @click="randomMatch()" >随机匹配</el-button>
          <el-button type="primary" @click="buildGroup">下一步</el-button>
        </div>
      </div>
      

      <div v-if="step == 3">
        <div class="group-teams">
          <GroupTeamShow
            :groupList="showList"
            :teamIndex="currentGroupIndex"
            :isPreview="isPreview">
          </GroupTeamShow>
        </div>
        <div class="btn-group center">
          <el-button type="primary" @click="step=2">返回编辑</el-button>
          <el-button type="primary" @click="build()">生成分组</el-button>
        </div>
      </div>
    </div> 
  </div>
</template>

<script>
import GroupSlider from '../components/GroupSlider'
import GroupTeam from './components/GroupTeam'
import GroupTeamShow from './components/GroupTeamShow'
import {mapGetters} from 'vuex'
import {calcGroups, checkIsPowTwo, cloneObj} from 'utils'
import Api from 'api/race'
export default {
  components: {
    GroupSlider,
    GroupTeam,
    GroupTeamShow
  },
  computed: {
    ...mapGetters({
      race_cup_groups: 'race_cup_groups', // 分组列表
      race_cup_teams: 'race_cup_teams' // 球队列表
    }),
    avgCount () { // 每组出线数量
      let n = parseFloat(this.race_cup_teams.length / this.form1.groupCount).toFixed(1)
      let ns = n.toString()
      return ns.split('.')[1] === '0' ? Number(n) : n
    },
    currentGroupIndex () {
      return this.race_cup_groups.indexOf(this.activeGroup)
    },
    unSelect () {
      let n = 0
      this.groupList.forEach(g => {
        g.forEach(it => {
          if (typeof it === 'string') {
            n++
          }
        })
      })
      return n
    }
  },
  created () {
    this.getTeams()
    // this.getGroup()
  },
  data () {
    return {
      isPreview: false,
      value: [],
      titleList: [
        '创建分组—步骤1',
        '创建分组—步骤2',
        '分组预览'
      ],
      step: 1,
      warnText: '每组最少参赛者数量为4，最大为8',
      warnText1: '出线的参赛者总数量必须保证为2的N次方(N≥1）',
      form1: {
        groupCount: 4, // 分组数量
        outletCount: 1, // 每组出线数量
        participantCount: ''
      },
      rules: {},
      activeGroup: {},
      groupList: [], // 所有球队分组列表
      groupLengthList: [], // 每个分组长度
      teams: [], // 当前小组
      oldTeamLength: 0,
      loading: false,
      showList: [],
      returnList: [], // 随机分组返回的列表
      selectedList: [] // 手动选择的分组列表
    }
  },
  methods: {
    getGroup () {
      Api.getCupGroup({matchId: this.$route.query.id}).then((res) => {
        console.log(res)
      })
    },
    // 生成分组
    generateGroup (len) {
      if (this.race_cup_groups.length && len === this.oldTeamLength) { // 分组数量一样
        return false
      } else {
        this.loading = true
        let list = []
        for (let i = 0; i < len; i++) {
          list.push({
            groupName: String.fromCharCode(65 + i),
            id: i
          })
        }
        if (len > 26) {
          list = list.splice(0, 26)
          for (let j = 0; j < (len - 26); j++) {
            list.push({
              groupName: 'A' + String.fromCharCode(65 + j + 1),
              id: j + 26
            })
          }
        }
        this.$store.commit('RACE_CUP_GROUPS', list)
        this.$set(this.race_cup_groups, 0, this.race_cup_groups[0])
        this.groupList = []
        for (let k = 0; k < len; k++) {
          this.groupList.push([])
        }
        this.groupLengthList = calcGroups(this.race_cup_teams.length, this.groupList)
        this.teams = this.groupList[0]
        this.$store.commit('RACE_CUP_TEAM_LIST', this.groupList)
        this.activeGroup = this.race_cup_groups[0]
      }
      this.oldTeamLength = len
    },
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.avgCount < 4 || this.avgCount > 8) {
            this.$message({
              message: this.warnText,
              type: 'warning'
            })
            return
          }
          if (this.form1.outletCount > this.race_cup_teams.length) {
            this.$message({
              message: '出线数量不能大于参赛球队数量',
              type: 'warning'
            })
            return
          }
          if (!checkIsPowTwo(this.form1.outletCount) || this.form1.outletCount < 2) {
            this.$message({
              message: this.warnText1,
              type: 'warning'
            })
            return
          }
          this.generateGroup(this.form1.groupCount)
          this.step = 2
          this.loading = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleChange (val) {
      let index = this.race_cup_groups.indexOf(val)
      if (index > -1) {
        this.teams = this.groupList[index]
      }
      this.activeGroup = val
    },
    handleSelect (obj) {
      this.value.push(obj.value.value)
      let activeIndex = this.race_cup_groups.indexOf(this.activeGroup) // 当前组
      this.groupList[activeIndex][obj.index] = obj.value
    },
    buildGroup () {
      if ((this.race_cup_teams.length - this.unSelect) > 0) {
        this.$message({
          message: '还有球队未分组哦',
          type: 'warning'
        })
      } else {
        if (this.returnList.length) {
          this.isPreview = false
          this.showList = this.returnList
        } else {
          let teamList = []
          for (let x = 0, xlen = this.groupList.length; x < xlen; x++) {
            let uList = []
            for (let y = 0, ylen = this.groupList[x].length; y < ylen; y++) {
              for (let m = 0, mlen = this.race_cup_teams.length; m < mlen; m++) {
                if (this.race_cup_teams[m].value === this.groupList[x][y]) {
                  uList.push({
                    iconUrl: this.race_cup_teams[m].iconUrl,
                    commingName: this.race_cup_teams[m].label
                  })
                }
              }
            }
            teamList.push({
              userList: uList
            })
          }
          this.showList = teamList
          // this.isPreview = true
        }
        this.step = 3
      }
    },
    // 随机分组
    randomMatch () {
      if (!this.selectedList.length) {
        this.selectedList = this.filterSelectTeam()
      }
      Api.randomMatch({
        cupGroups: this.selectedList,
        matchId: this.$route.query.id,
        groupCount: this.form1.groupCount,
        outletCount: this.form1.outletCount,
        participantCount: this.form1.participantCount
      }).then((res) => {
        let groupList = JSON.parse(JSON.stringify(this.groupList))
        this.returnList = res.data.cupGroups
        let result = res.data.cupGroups
        for (let i = 0, l = result.length; i < l; i++) {
          var group = result[i].userList
          for (let j = 0, jlen = group.length; j < jlen; j++) {
            groupList[i][j] = group[j].userId
          }
        }
        this.groupList = groupList
      })
    },
    getTeams () {
      Api.getSeedUser({matchId: this.$route.query.id}).then((res) => {
        this.$store.commit('RACE_CUP_TEAMS', res.data)
      })
    },
    // 请求生成分组
    build () {
      this.$confirm('确定要生成分组?', '提示', {
        type: 'warning'
      }).then(() => {
        let list = this.filterSelectTeam()
        Api.CupBuildGroup({
          cupGroups: list,
          matchId: this.$route.query.id,
          groupCount: this.form1.groupCount,
          outletCount: this.form1.outletCount,
          participantCount: this.form1.participantCount
        }).then((res) => {
          this.$router.push({
            path: '/race/detail/manage/cup',
            query: this.$route.query
          })
        })
      })
    },
    filterSelectTeam () {
      let list = []
      for (let i = 0, l = this.groupList.length; i < l; i++) {
        let u = []
        let group = this.groupList[i]
        for (let j = 0, jlen = group.length; j < jlen; j++) {
          if (typeof group[j] === 'string') {
            u.push({
              userId: group[j]
            })
          }
        }
        list.push({
          gradePage: i + 1,
          userList: u
        })
      }
      this.selectedList = cloneObj(list)
      return list
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../../styles/var.scss';
.btn-groups{
  margin-top:40px;
  width:100%;
}
.team-num{
  color: $primary-color;
  font-size: 18px;
}
.top-line{
  line-height: 36px;
}
.inline{
  display: inline-block;
}
.text-right{
  text-align: right;
}
.tips{
  color:#999;
  font-size:12px;
  padding-left: 10px;
}
.group-teams{
  padding: 20px;
  border:1px solid #f0f0f0;
  margin: 20px 0;
}
.left-team{
  margin-top: 30px;
  text-align: right;
  span{
    color:$primary-color;
  }
}
.btn-group{
  width: 100%;
  margin-top: 30px;
}

</style>
